<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>物流运费计算测试</title>
    <style>
        body { font-family: Arial, sans-serif; margin: 20px; }
        .test-section { margin: 20px 0; padding: 15px; border: 1px solid #ccc; }
        .success { color: green; }
        .error { color: red; }
        .info { color: blue; }
        .test-btn { padding: 8px 12px; background: #007bff; color: white; border: none; border-radius: 4px; cursor: pointer; margin: 5px; }
        .test-btn:hover { background: #0056b3; }
        .input-group { margin: 10px 0; }
        .input-group label { display: block; margin-bottom: 5px; font-weight: bold; }
        .input-group input { width: 100%; padding: 8px; border: 1px solid #ddd; border-radius: 4px; }
        .result-box { background: #f8f9fa; padding: 15px; border-radius: 4px; margin-top: 10px; }
        .result-item { margin: 5px 0; }
    </style>
</head>
<body>
    <h1>物流运费计算测试</h1>
    
    <div class="test-section">
        <h3>运费计算规则</h3>
        <div class="info">
            <strong>运费规则：</strong><br>
            • 10km以内：统一10元<br>
            • 大于10km：每200km加8元<br>
            <br>
            <strong>示例：</strong><br>
            • 5km -> ¥10<br>
            • 50km -> ¥11.60<br>
            • 200km -> ¥18<br>
            • 500km -> ¥30
        </div>
    </div>
    
    <div class="test-section">
        <h3>1. 测试物流运费计算</h3>
        <div class="input-group">
            <label>仓库地址（发货地址）:</label>
            <input type="text" id="warehouseAddress" value="北京市朝阳区三里屯街道工体北路8号院" placeholder="输入仓库地址">
        </div>
        <div class="input-group">
            <label>收货地址:</label>
            <input type="text" id="deliveryAddress" value="北京市海淀区中关村大街1号" placeholder="输入收货地址">
        </div>
        <button class="test-btn" onclick="testLogisticsCalculation()">计算运费</button>
        <div id="calculationResult"></div>
    </div>
    
    <div class="test-section">
        <h3>2. 测试订单创建（包含物流计算）</h3>
        <button class="test-btn" onclick="testOrderWithLogistics()">创建测试订单</button>
        <div id="orderResult"></div>
    </div>
    
    <div class="test-section">
        <h3>3. 测试不同距离的运费</h3>
        <button class="test-btn" onclick="testDifferentDistances()">测试不同距离</button>
        <div id="distanceTestResult"></div>
    </div>
    
    <div class="test-section">
        <h3>4. 调试信息</h3>
        <div id="debugInfo"></div>
    </div>

    <!-- 引入必要的脚本 -->
    <script src="js/api.js"></script>
    
    <script>
        // 重写console.log来显示在页面上
        const originalLog = console.log;
        const originalWarn = console.warn;
        const originalError = console.error;
        
        function addToConsole(message, type = 'info') {
            const debugDiv = document.getElementById('debugInfo');
            const timestamp = new Date().toLocaleTimeString();
            debugDiv.innerHTML += `<div class="${type}">[${timestamp}] ${message}</div>`;
            debugDiv.scrollTop = debugDiv.scrollHeight;
        }
        
        console.log = function(...args) {
            originalLog.apply(console, args);
            addToConsole(args.join(' '), 'info');
        };
        
        console.warn = function(...args) {
            originalWarn.apply(console, args);
            addToConsole(args.join(' '), 'error');
        };
        
        console.error = function(...args) {
            originalError.apply(console, args);
            addToConsole(args.join(' '), 'error');
        };
        
        // 测试物流运费计算
        async function testLogisticsCalculation() {
            const resultDiv = document.getElementById('calculationResult');
            const warehouseAddress = document.getElementById('warehouseAddress').value;
            const deliveryAddress = document.getElementById('deliveryAddress').value;
            
            if (!warehouseAddress || !deliveryAddress) {
                resultDiv.innerHTML = '<div class="error">请填写完整的地址信息</div>';
                return;
            }
            
            try {
                console.log('开始计算物流运费...');
                console.log('仓库地址:', warehouseAddress);
                console.log('收货地址:', deliveryAddress);
                
                const response = await fetch('http://localhost:8000/api/logistics/calculate', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        delivery_address: deliveryAddress
                    })
                });
                
                const result = await response.json();
                console.log('物流计算结果:', result);
                
                if (result.success) {
                    const data = result.data;
                    resultDiv.innerHTML = `
                        <div class="result-box">
                            <div class="success">✓ 计算成功</div>
                            <div class="result-item"><strong>运费:</strong> ¥${data.shipping_fee.toFixed(2)}</div>
                            ${data.distance_km ? `<div class="result-item"><strong>距离:</strong> ${data.distance_km} km</div>` : ''}
                            ${data.duration_h ? `<div class="result-item"><strong>预计耗时:</strong> ${data.duration_h} 小时</div>` : ''}
                            <div class="result-item"><strong>仓库地址:</strong> ${data.warehouse_address}</div>
                            <div class="result-item"><strong>收货地址:</strong> ${data.delivery_address}</div>
                            <div class="result-item"><strong>是否使用API计算:</strong> ${data.calculated ? '是' : '否'}</div>
                            ${data.error ? `<div class="error">警告: ${data.error}</div>` : ''}
                        </div>
                    `;
                } else {
                    resultDiv.innerHTML = `
                        <div class="error">✗ 计算失败: ${result.error}</div>
                        ${result.data ? `
                            <div class="result-box">
                                <div class="info">使用默认运费:</div>
                                <div class="result-item"><strong>运费:</strong> ¥${result.data.shipping_fee.toFixed(2)}</div>
                            </div>
                        ` : ''}
                    `;
                }
            } catch (error) {
                resultDiv.innerHTML = '<div class="error">✗ 计算错误: ' + error.message + '</div>';
                console.error('计算错误:', error);
            }
        }
        
        // 测试订单创建（包含物流计算）
        async function testOrderWithLogistics() {
            const resultDiv = document.getElementById('orderResult');
            
            try {
                console.log('开始创建测试订单...');
                
                const orderData = {
                    items: [
                        {
                            productId: 'F001',
                            product_name: '测试商品',
                            price: 100.0,
                            quantity: 1
                        }
                    ],
                    shippingAddress: {
                        name: '测试用户',
                        phone: '13800138000',
                        address: document.getElementById('deliveryAddress').value || '北京市海淀区中关村大街1号'
                    },
                    paymentMethod: 'alipay',
                    discount: 0
                };
                
                console.log('订单数据:', orderData);
                
                const result = await window.api.createOrder(orderData);
                console.log('订单创建结果:', result);
                
                if (result.success) {
                    const order = result.data;
                    resultDiv.innerHTML = `
                        <div class="result-box">
                            <div class="success">✓ 订单创建成功</div>
                            <div class="result-item"><strong>订单号:</strong> ${order.order_number}</div>
                            <div class="result-item"><strong>商品总额:</strong> ¥${(order.total_amount - order.shipping_fee).toFixed(2)}</div>
                            <div class="result-item"><strong>运费:</strong> ¥${order.shipping_fee.toFixed(2)}</div>
                            <div class="result-item"><strong>订单总额:</strong> ¥${order.total_amount.toFixed(2)}</div>
                            ${order.logistics ? `
                                <div class="result-item"><strong>物流信息:</strong></div>
                                <div class="result-item" style="margin-left: 20px;">
                                    ${order.logistics.distance_km ? `距离: ${order.logistics.distance_km} km<br>` : ''}
                                    ${order.logistics.duration_h ? `预计耗时: ${order.logistics.duration_h} 小时<br>` : ''}
                                    是否使用API计算: ${order.logistics.calculated ? '是' : '否'}
                                </div>
                            ` : ''}
                        </div>
                    `;
                } else {
                    resultDiv.innerHTML = '<div class="error">✗ 订单创建失败: ' + result.error + '</div>';
                }
            } catch (error) {
                resultDiv.innerHTML = '<div class="error">✗ 创建订单错误: ' + error.message + '</div>';
                console.error('创建订单错误:', error);
            }
        }
        
        // 测试不同距离的运费
        function testDifferentDistances() {
            const resultDiv = document.getElementById('distanceTestResult');
            
            // 运费计算函数（前端模拟）
            function calculateShippingFee(distance_km) {
                if (distance_km <= 10) {
                    return 10.0;
                } else {
                    const excess_km = distance_km - 10;
                    const additional_fee = (excess_km / 200) * 8;
                    return Math.round((10.0 + additional_fee) * 100) / 100;
                }
            }
            
            const testDistances = [5, 10, 50, 100, 200, 500, 1000];
            let resultHTML = '<div class="result-box"><h4>运费计算示例:</h4>';
            
            testDistances.forEach(distance => {
                const fee = calculateShippingFee(distance);
                resultHTML += `<div class="result-item">距离 ${distance}km -> 运费 ¥${fee.toFixed(2)}</div>`;
            });
            
            resultHTML += '</div>';
            resultDiv.innerHTML = resultHTML;
        }
        
        // 页面加载完成后运行
        window.addEventListener('load', () => {
            console.log('物流运费计算测试页面加载完成');
        });
    </script>
</body>
</html>
